<?php

namespace App\Console\Commands;

use App\Models\BankSubAccountFinance;
use App\Models\SyncTaskConfig;
use App\SDK\PingAn\Service;
use Illuminate\Console\Command;

class BankSubAccountFinanceCmd extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:bank-sub-account-finance-cmd';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $this->pingan();
    }

    public function _pingan($queryData){
        $queryData["requestId"] = uniqid();
        $service = Service::instance();
        $method = 'business/accountitem/v2/accountitem001';//请求方法，对应请求地址的最后部份
        $result = $service->invoke($queryData, $method);
        $total = $result["body"]["Data"]["total"];
        if(!$total) return $total;
        $inserts = [];
        foreach ($result["body"]["Data"]["records"] as $record){
            $inserts[] = [
                "bill_no"=>$record["bankBusinessId"],
                "loan_type"=>$record["loanType"],
                "amount"=>$record["amount"],
                "balance"=>$record["balance"],
                "use"=>$record["use"],
                "summary"=>$record["summary"],
                "create_time"=>$record["createdTime"],
                "update_time"=>$record["modifiedTime"],
            ];
        }
        BankSubAccountFinance::query()->upsert($inserts,["bill_no"],[
            "loan_type",
            "amount",
            "balance",
            "use",
            "summary",
            "create_time",
            "update_time",
        ]);
        return $total;
    }

    public function pingan(): void
    {
        $model = SyncTaskConfig::query()->where("key","bank_last_time")->first();

        $page = 1;
        $pageSize = 300;
        $queryData = [
            'certificateNo'=>'91330183MAE038NT4F',
            'certificateType'=>'989',
            'account'=>'15818756820039',
            'pageNo'=>$page,
            'pageSize'=>$pageSize,
        ];
        if(!empty($model->value)){
            $queryData["beginDate"] = $model->value;
        }
        $total = $this->_pingan($queryData);
        $totalPage = ceil($total / $pageSize);
        for($page=2;$page<=$totalPage;$page++){
            $queryData["pageNo"] = $page;
            $this->_pingan($queryData);
        }
        $model->value = date("Y-m-d 00:00:00",time() - 86400);
        $model->save();

    }
}
